package chooongg.base.utils

import android.text.InputFilter
import android.text.Spanned
import android.text.method.ReplacementTransformationMethod
import android.widget.EditText
import java.math.BigDecimal
import java.math.RoundingMode

/* 字符串工具类 */

/**
 * 是空或空串或空格串
 */
fun isSpace(str: String?): Boolean {
    if (str == null) return true
    var i = 0
    val len = str.length
    while (i < len) {
        if (!Character.isWhitespace(str[i])) return false
        ++i
    }
    return true
}

fun BigDecimal?.toCurrency(round: RoundingMode = RoundingMode.HALF_UP): String {
    if (this == null) return "0.00"
    if (this.toDouble()<0) return "0.00"
    return setScale(2, round).toString()
}



fun BigDecimal?.toCurrencyOrNull(round: RoundingMode = RoundingMode.HALF_UP): String {
    if (this == null) return "未知"
    return setScale(2, round).toString()
}

/**
 * 禁止EditText输入空格
 */
fun EditText.inhibitInputSpace() {
    val newFilters = ArrayList<InputFilter>(filters.asList())
    val filter = object : InputFilter {
        override fun filter(source: CharSequence?, start: Int, end: Int, dest: Spanned?, dstart: Int, dend: Int): CharSequence? {
            return if (source == " ") ""
            else null
        }
    }
    newFilters.add(filter)
    filters = newFilters.toTypedArray()
}

/**
 * 禁止EditText输入特殊字符
 */
fun EditText.inhibitInputSpeChat() {
    val newFilters = ArrayList<InputFilter>(filters.asList())
    val filter = object : InputFilter {
        override fun filter(source: CharSequence?, start: Int, end: Int, dest: Spanned?, dstart: Int, dend: Int): CharSequence? {
            val speChat = "[`~!@#$%^&*()+=|{}':;,\\[\\].<>/?！￥…（）—【】‘；：”“’。，、？]".toRegex()
            return if (speChat.matches(source?.toString() ?: "")) ""
            else null
        }
    }
    newFilters.add(filter)
    filters = newFilters.toTypedArray()
}

/**
 * 小写字母转大写
 */
class UppercaseTransformation : ReplacementTransformationMethod() {
    override fun getOriginal(): CharArray {
        return charArrayOf('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')
    }

    override fun getReplacement(): CharArray {
        return charArrayOf('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z')
    }
}